<template>
  <div class="w-full statistical-center">
    <statisticalHeader />
    <div class="px-40px pb-60px m--9px flex flex-1 gap-18px flex-col">
      <div class="flex items-center justify-between">
        <div class="flex items-center gap-12px text-28px fw-700">
          <div class="flex items-center">
            <el-date-picker
              popper-class="popper-date-class"
              v-model="queryDate"
              type="daterange"
              placeholder="请选择日期"
              value-format="YYYYMMDD"
              :clearable="false"
            />
          </div>
          <ClassStudentCascader @change="cascaderChange" />
        </div>
        <div>
          <aiGenerateReport :sendContent="sendContent" :roleId="50" />
        </div>
      </div>
      <el-scrollbar
        ref="echartWarpRef"
        class="statistical-center-content"
        view-class="pb-60px flex gap-20px flex-wrap"
        v-loading="loading"
      >
        <div class="echart-card pt-15px w-910px h-434px">
          <Echart
            :width="getViewportPx(910)"
            :height="getViewportPx(393)"
            :options="healthChartOption"
          />
        </div>
        <div class="echart-card pt-15px w-910px h-434px">
          <Echart
            :width="getViewportPx(910)"
            :height="getViewportPx(393)"
            :options="sleepChartOption"
          />
        </div>
        <div class="echart-card pt-15px w-910px h-434px">
          <Echart
            :width="getViewportPx(910)"
            :height="getViewportPx(393)"
            :options="avgStepsChartOption"
          />
        </div>
        <div class="echart-card pt-15px w-910px h-434px">
          <Echart
            :width="getViewportPx(910)"
            :height="getViewportPx(393)"
            :options="wristTempAbnormalChartOption"
          />
        </div>
      </el-scrollbar>
    </div>
  </div>
</template>
<script setup lang="ts">
import { getViewportPx } from '@/utils/formatter'
import { statisticalCenterApi } from '@/api/school/statisticalCenter/index'
import { useBarOptions } from '@/hooks/chart/useBarOptions'
import { useLineOptions } from '@/hooks/chart/useLineOptions'
import statisticalHeader from './components/statisticalHeader.vue'
import aiGenerateReport from './components/aiGenerateReport.vue'
import { getAxisNameConfig, getDataZoomConfig } from './utils'
import { formatDate } from '@/utils/formatTime'
import { isBoolean } from '@/utils/is'

const healthData: any = ref([])
const sleepData: any = ref([])
const nowDateStr = formatDate(new Date(), 'YYYYMMDD')
const queryDate = ref([nowDateStr, nowDateStr])
const loading = ref(true)
const cascaderParams: any = ref({})
const pathLabels = ref([])
// 查询参数
const queryParams = computed(() => {
  return {
    queryDate: queryDate.value[0],
    startTime: queryDate.value[0],
    endTime: queryDate.value[1],
    ...cascaderParams.value
  }
})
// 发送内容
const sendContent = computed(() => {
  const baseData = {
    startTime: queryParams.value.startTime,
    endTime: queryParams.value.endTime,
    type: pathLabels.value.length - 1,
    target: pathLabels.value.join('-')
  }
  return `${JSON.stringify({
    ...baseData,
    data: healthData.value
  })}${JSON.stringify({
    ...baseData,
    data: sleepData.value
  })}`
})
// 请求接口
const requestApiMap = computed(() => {
  let healthApi = statisticalCenterApi.getHealthReport
  let sleepApi = statisticalCenterApi.getSleepReport
  if (queryParams.value.studentId) {
    healthApi = statisticalCenterApi.getStudentHealthReport
    sleepApi = statisticalCenterApi.getStudentSleepReport
  } else if (queryParams.value.classId) {
    healthApi = statisticalCenterApi.getClassHealthReport
    sleepApi = statisticalCenterApi.getClassSleepReport
  }
  return {
    getHealthReport: healthApi,
    getSleepReport: sleepApi
  }
})
const cascaderChange = async (params, cascaderPathLabels) => {
  cascaderParams.value = params
  pathLabels.value = cascaderPathLabels
}

const init = async () => {
  try {
    loading.value = true
    const list = await requestApiMap.value.getHealthReport({
      ...queryParams.value
    })
    healthData.value = list || []
    const sleepList = await requestApiMap.value.getSleepReport({
      ...queryParams.value
    })
    sleepData.value = sleepList || []
  } catch (error) {
    console.log(error)
  } finally {
    loading.value = false
  }
}
const healthChartOption = computed(() => {
  const isSchoolLevel =
    queryParams.value.schoolCode && !queryParams.value?.classId && !queryParams.value?.studentId
  return useBarOptions([], {
    title: {
      text: queryParams.value.studentId ? '运动时长' : '日平均运动时长',
      left: 'center'
    },
    grid: {
      top: getViewportPx(100, true),
      right: getViewportPx(15),
      left: getViewportPx(80)
    },
    dataZoom: healthData.value.length > 6 && [getDataZoomConfig()],
    legend: {
      right: getViewportPx(15)
    },
    yAxis: {
      ...getAxisNameConfig('单位：分钟')
    },
    xAxis: {
      data: healthData.value?.map?.((item) => item.className || item.studentName || item.date) || []
    },
    series: [
      {
        name: queryParams.value.studentId ? '运动时长' : '人均运动时长',
        barWidth: getViewportPx(20),
        itemStyle: {
          color: '#8945FF'
        },
        data:
          healthData.value?.map?.((item) => ({
            name: item.className || item.studentName || item.date,
            value: Math.floor((item.avgDurationSeconds || item.durationSeconds / 60) * 100) / 100
          })) || []
      },
      isSchoolLevel && {
        name: '达标率',
        type: 'line',
        symbol: 'circle',
        itemStyle: {
          color: '#47D147'
        },
        tooltip: {
          valueFormatter(value) {
            return `${value}%`
          }
        },
        data:
          healthData.value?.map?.((item) => ({
            name: item.className || item.studentName || item.date,
            value: item.passRatePercent
          })) || []
      }
    ]
  }).baseOptions
})
const sleepChartOption = computed(() => {
  return useLineOptions([], {
    title: {
      text: queryParams.value.studentId ? '睡眠时长' : '日平均睡眠时长',
      left: 'center'
    },
    grid: {
      top: getViewportPx(100, true),
      right: getViewportPx(15),
      left: getViewportPx(80)
    },
    dataZoom: sleepData.value.length > 6 && [getDataZoomConfig()],
    yAxis: {
      ...getAxisNameConfig('单位：分钟')
    },
    series: [
      {
        name: queryParams.value.studentId ? '睡眠时长' : '人均睡眠时长',
        itemStyle: {
          color: '#47D147'
        },
        lineStyle: {
          type: 'dashed'
        },
        data:
          sleepData.value?.map?.((item) => ({
            name: item.className || item.studentName || item.date,
            value: item.avgSleepMinutes || item.sleepMinutes || 0
          })) || []
      }
    ]
  }).baseOptions
})
const avgStepsChartOption = computed(() => {
  return useBarOptions([], {
    title: {
      text: queryParams.value.studentId ? '步数与运动量' : '日平均步数与运动量',
      left: 'center'
    },
    grid: {
      top: getViewportPx(100, true),
      right: getViewportPx(15),
      left: getViewportPx(80)
    },
    dataZoom: healthData.value.length > 6 && [getDataZoomConfig()],
    legend: {
      right: getViewportPx(15)
    },
    xAxis: {
      data: healthData.value?.map?.((item) => item.className || item.studentName || item.date) || []
    },
    yAxis: {
      ...getAxisNameConfig('单位：步')
    },
    series: [
      {
        name: queryParams.value.studentId ? '运动步数' : '人均运动步数',
        barWidth: getViewportPx(20),
        itemStyle: {
          color: '#00BFFF'
        },
        data:
          healthData.value?.map?.((item) => ({
            name: item.className || item.studentName || item.date,
            value: item.avgSteps || item.steps || 0
          })) || []
      },
      {
        name: '运动量：千卡',
        type: 'line',
        symbol: 'circle',
        itemStyle: {
          color: '#47D147'
        },
        data:
          healthData.value?.map?.((item) => ({
            name: item.className || item.studentName,
            value: item.avgCalories || item.calories || 0
          })) || []
      }
    ]
  }).baseOptions
})

const wristTempAbnormalChartOption = computed(() => {
  let axisName = '单位：个'
  let isStudentLevel = queryParams.value.studentId
  if (queryParams.value?.classId) {
    axisName = '单位：天'
  }
  if (queryParams.value?.studentId) {
    axisName = '是否异常'
  }
  return useBarOptions([], {
    title: {
      text: '实时腕温异常监测',
      left: 'center'
    },
    grid: {
      top: getViewportPx(100, true)
    },
    dataZoom: healthData.value.length > 6 && [getDataZoomConfig()],
    xAxis: {
      data: healthData.value?.map?.((item) => item.className || item.studentName || item.date) || []
    },
    yAxis: {
      ...getAxisNameConfig(axisName),
      ...(isStudentLevel && {
        axisLabel: {
          formatter: function (value) {
            // 根据值的位置返回相应标签
            // value 为 0 表示正常，value 为 1 表示异常
            if (value === 0) {
              return '正常'
            } else if (value === 1) {
              return '异常'
            }
            return ''
          }
        },
        // 设置 Y 轴的最大值为 1，确保只有两个刻度点（0 和 1）
        max: 1
      })
    },
    // 学生级别时不显示图例
    tooltip: {
      ...(isStudentLevel && {
        formatter: (params) => {
          const param = params[0]
          const dataItem = param.data
          const date = dataItem.name
          const tempStatus = dataItem.value === 0 ? (dataItem.wristTemp ? '正常' : '未知') : '异常'
          const wristTemp = dataItem.wristTemp || '未知'

          // 格式化 tooltip 显示内容
          return (
            `${date}<br />` +
            `${param.marker}` +
            `腕温${tempStatus}<br />` +
            `温度：${wristTemp || '--'}`
          )
        }
      })
    },
    series: [
      // {
      //   name: '腕温正常',
      //   barMaxWidth: getViewportPx(20),
      //   barMinWidth: getViewportPx(2),
      //   itemStyle: {
      //     color: '#17E3BE'
      //   },
      //   data:
      //     healthData.value?.map?.((item) => ({
      //       name: item.className || item.studentName || item.date,
      //       value: item.wristTempNormalCount
      //     })) || []
      // },
      {
        name: '腕温异常',
        barMaxWidth: getViewportPx(20),
        barMinWidth: getViewportPx(2),
        itemStyle: {
          color(item) {
            const itemData = item.data
            if (isBoolean(itemData.wristTempNormal)) {
              return itemData.wristTempNormal ? '#47D147' : '#FC5C53'
            }
            return item?.value > 0 ? '#FC5C53' : '#47D147'
          }
        },
        ...(isStudentLevel && {
          label: {
            formatter: function (params) {
              // 柱状图顶部显示"正常"或"异常"而不是0或1
              return params.value === 0 ? '正常' : '异常'
            }
          }
        }),
        data:
          healthData.value?.map?.((item) => ({
            name: item.className || item.studentName || item.date,
            value:
              item.wristTempAbnormalCount ||
              item.wristTempAbnormalDays ||
              ('wristTempNormal' in item && Number(!item.wristTempNormal)) ||
              0,
            wristTempNormal: item.wristTempNormal,
            wristTemp: item.wristTemp
          })) || []
      }
    ]
  }).baseOptions
})
watch(
  () => queryParams.value,
  () => {
    init()
  },
  {
    immediate: true
  }
)
</script>
<style lang="scss" scoped>
@import url('./index.scss');
</style>
